﻿using BasicInformation.Domain;
using BasicInformation.Infrastructure.Iml;
using BasicInformation.Infrastructure.Interface;
using BasicInformation.ReadAPI.Application.Command.VehicleCommand;
using MediatR;
using Microsoft.AspNetCore.Mvc.RazorPages;
using PublicCommon;

namespace BasicInformation.ReadAPI.Application.CommandHandler.VehicleCommandHandler
{
    public class VehicleListCommandHandler : IRequestHandler<VehicleListCommand, PageResult<Vehicle>>
    {
        private readonly IVehicleRepository vehicleRepository;

        public VehicleListCommandHandler(IVehicleRepository vehicleRepository)
        {
            this.vehicleRepository = vehicleRepository;
        }

        public async Task<PageResult<Vehicle>> Handle(VehicleListCommand request, CancellationToken cancellationToken)
        {
            var list = vehicleRepository.GetList().Result.Where(x => !x.IsDel).AsQueryable();
            if (!string.IsNullOrEmpty(request.FactoryModel))
            {
                list = list.Where(x => x.FactoryModel.Contains(request.FactoryModel));
            }
            if (!string.IsNullOrEmpty(request.LicenseNumber))
            {
                list = list.Where(x => x.LicenseNumber.Contains(request.LicenseNumber));
            }
            if (!string.IsNullOrEmpty(request.DriversName))
            {
                list = list.Where(x => x.DriversName.Contains(request.DriversName));
            }
            if (!string.IsNullOrEmpty(request.SubordCompan))
            {
                list = list.Where(x => x.SubordCompan.Contains(request.SubordCompan));
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            var pagelist = list.OrderByDescending(x => x.Id).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return new PageResult<Vehicle>
            {
                List = pagelist,
                PageCount = pageCount,
                TotalCount = totalCount
            };
        }
    }
}
